import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';

import './message.scoped.less';
const Message = (props) => {
  const [opacity, setOpacity] = useState(false);
  useEffect(() => {
    setOpacity(true);
  }, []);
  return (
    <div className={`message ${props.className || ''} ${opacity ? 'show' : ''}`}>
      <div>{props.content}</div>
    </div>
  );
};

function createMessage() {}

createMessage.prototype.create = function (props) {
  this.div = document.createElement('div');
  document.body.appendChild(this.div);
  this.timer = setTimeout(() => {
    this.close();
  }, 3000);
};

createMessage.prototype.success = function (text) {
  ReactDOM.render(<Message className="success" content={text}></Message>, this.div);
};

createMessage.prototype.error = function (text) {
  ReactDOM.render(<Message className="error" content={text}></Message>, this.div);
};

createMessage.prototype.warn = function (text) {
  ReactDOM.render(<Message className="warn" content={text}></Message>, this.div);
};

createMessage.prototype.info = function (text) {
  ReactDOM.render(<Message className="info" content={text}></Message>, this.div);
};

createMessage.prototype.close = function (props) {
  this.div.parentNode.removeChild(this.div);
  this.div = null;
  clearTimeout(this.timer);
};

function createTip() {
  const tip = new createMessage();
  tip.create();
  return tip;
}

const message = {
  success: (text) => {
    const tip = createTip();
    tip.success(text);
  },
  error: (text) => {
    const tip = createTip();
    tip.error(text);
  },
  warn: (text) => {
    const tip = createTip();
    tip.warn(text);
  },
  info: (text) => {
    const tip = createTip();
    tip.info(text);
  },
};

export default message;
